import 'package:flutter/material.dart';
import '../../utils/G.dart';

class Favorite extends StatefulWidget {
  const Favorite({Key? key}) : super(key: key);

  @override
  _FavoriteState createState() => _FavoriteState();
}

class _FavoriteState extends State<Favorite> {
  List list = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('我的收藏'),
          centerTitle: true,
        ),
        body: FutureBuilder(
            future: G.api.favorite.list(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                var res = snapshot.data as Map;
                if (res['status'] == 200) {
                  list = res['data'];

                  return list.isNotEmpty
                      ? _renderFavoriteList()
                      : const Center(
                          child: Text('空空如也~'),
                          heightFactor: 10,
                        );
                } else {
                  // 报错
                  G.error('接口请求失败');
                }
              } else if (snapshot.hasError) {
                return Center(
                  child: Text("${snapshot.error}"),
                );
              }

              return G.loader();
            }));
  }

  Widget _renderFavoriteList() {
    return ListView(
      scrollDirection: Axis.vertical,
      shrinkWrap: true,
      padding: const EdgeInsets.all(10),
      physics: const BouncingScrollPhysics(),
      children: List<Widget>.generate(list.length, (int index) {
        return Container(
            margin: const EdgeInsets.fromLTRB(0, 0, 0, 20),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: const BorderRadius.all(Radius.circular(10)),
                boxShadow: [
                  BoxShadow(
                      color: Colors.grey.shade300,
                      offset: const Offset(5, 5),
                      blurRadius: 10)
                ]),
            child: ClipRRect(
                borderRadius: const BorderRadius.all(Radius.circular(10)),
                child: _renderFavoriteItem(list[index])));
      }),
    );
  }

  Widget _renderFavoriteItem(Map item) {
    return ListTile(
      onTap: () {
        Map<String, dynamic> p = {'id': item['id']};
        G.router
            .navigateTo(context, '/product_detail' + G.parseQuery(params: p));
      },
      leading: G.imageWidget(item['image'], width: 100, height: 100),
      title: Text(
        item['store_name'].toString(),
        style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
        overflow: TextOverflow.ellipsis,
      ),
      subtitle: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text("￥ " + item['price'].toString()),
          OutlinedButton(
              onPressed: () async {
                var res = await G.api.favorite.del(item['product_id']);
                if (res['status'] == 200) {
                  setState(() {
                    list.removeWhere(
                        (element) => element['id'] == item['product_id']);
                  });
                } else {
                  G.error('删除失败');
                }
              },
              child: const Text('删除'))
        ],
      ),
    );
  }
}
